package com.fyp.ptma.dao.repository;

import java.util.List;

import javax.persistence.PersistenceException;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import com.fyp.ptma.dao.exception.AuthenticationException;
import com.fyp.ptma.dao.repository.irepository.IUserDao;
import com.fyp.ptma.model.Application;
import com.fyp.ptma.model.User;

@Repository
@Scope("prototype")
public class UserDao implements IUserDao {

	@Autowired
	private SessionFactory sessionFactory;

	public Session openSession() {
		return sessionFactory.getCurrentSession();
	}

	public Long save(Object objToSave) throws PersistenceException,
			ConstraintViolationException {

		this.openSession().save(objToSave);
		return ((User) objToSave).getId();
	}

	public Long update(Object objToUpdate) throws PersistenceException {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean delete(Object objToDelete) throws PersistenceException,
			ConstraintViolationException {
		// TODO Auto-generated method stub
		return false;
	}

	public List<Application> getAllApplications(User user)
			throws HibernateException {
		Session session = this.openSession();
		Criteria criteria =	session.createCriteria(Application.class);
		criteria.add(Restrictions.eq("user", user));
		@SuppressWarnings("unchecked")
		List<Application> applications = criteria.list();
		return applications;
	}

	public Application getApplication(User user) throws HibernateException {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean authenticateLogin(User user) throws AuthenticationException,
			HibernateException {

		Session session = this.openSession();

		Criteria criteria = session.createCriteria(User.class);
		criteria.add(Restrictions.eq("email", user.getEmail()));

		User userDB = (User) criteria.uniqueResult();

		return userDB.getPassword().equals(user.getPassword());

	}

	public User getUserByEmail(String email) throws HibernateException,UsernameNotFoundException {
		Session session = this.openSession();

		Criteria criteria = session.createCriteria(User.class);
		criteria.add(Restrictions.eq("email", email));

		User userDB = (User) criteria.uniqueResult();
		return userDB;
	}

	@Override
	public void saveOrUpdate(Object objToSave) throws PersistenceException,
			ConstraintViolationException {
		 this.openSession().save(objToSave);
		
	}

}
